import React, { Component } from 'react'
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import {Button, Modal, Space, Tabs, Tag} from "antd";
import { exportSheetTable } from '@/utils/exportTable.js';
import { apiGetProviderList } from '@/request/callReconciliation/accountManage.js';
import { apiGetMhcOrderBillPage,apiMhcOrderBillExport } from '@/request/callReconciliation/reconcileOrder.js';

import _ from 'lodash';
import moment from "moment/moment";

//对账订单
class ReconcileOrder extends Component {
  state = {
    loading: false,
    columns: [
      {
        title: "订单编号",
        dataIndex: "orderId",
        key: "orderId",
      },
      {
        title: "服务",
        dataIndex: "serviceType",
        key: "serviceType",
        render: (text, record) => {
          let serviceType = ''
          switch (text) {
            case 'FEED':
              serviceType = '喂养'
                  break;
            case 'CARE':
              serviceType = '洗护'
              break;
          }
          let skuInfo = JSON.parse(record.skuInfo),skuInfoStr = ''
          if (!_.isEmpty(skuInfo)){
            skuInfoStr = skuInfo.specValues.map(item=>{
              return item.specsValue
            }).join('/')
          }
          return <div style={{ width: 200, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
            {serviceType} | {skuInfoStr}
          </div>
        }
      },
      {
        title: "服务时间",
        dataIndex: "serviceDate",
        key: "serviceDate",
        render: (text, record) => {
          return <Space>
            <span>{text}</span>
            <span>{record.serviceWeek}</span>
            <span>{record.serviceStartTime}</span>~
            <span>{record.serviceFinishTime}</span>
            {record.orderDetailType === 1 && <Tag color="red">变更</Tag>}
          </Space>
        }
      },
      {
        title: "金额(元)",
        dataIndex: "orderAmount",
        key: "orderAmount",
        render: (text) => {
          return <React.$Price price={text}/>
        }
      },
      {
        title: "实付金额(元)",
        dataIndex: "payAmount",
        key: "payAmount",
        render: (text) => {
          return <React.$Price price={text}/>
        }
      },
      {
        title: "退款金额(元)",
        dataIndex: "sumRefundPrice",
        key: "sumRefundPrice",
        render: (text) => {
          return <React.$Price price={text || 0}/>
        }
      },
      {
        title: "抽佣比例",
        dataIndex: "commissionRatio",
        key: "commissionRatio",
        render: (text) => {
          return text ? React.$transNum(text, 2, -2) + '%' : 0 + '%'
        }
      },
      {
        title: "服务者所得(元)",
        dataIndex: "settlementAmount",
        key: "settlementAmount",
        render: (text,record) => {
          return record.commissionStatus === '1' ? <React.$Price price={text}/> : '-'
        }
      },
      {
        title: "平台所得(元)",
        dataIndex: "commissionAmount",
        key: "commissionAmount",
        render: (text,record) => {
          return record.commissionStatus === '1' ? <React.$Price price={text}/> : '-'
        }
      },
      {
        title: "服务者",
        dataIndex: "servicerName",
        key: "servicerName",
        render: (text, record) => {
          return record.orderStatus === 'WAIT_ORDER_TAKING' ? '-' : <TheButton onClick={()=>this.onServeView(record.servicerId)}>{text}</TheButton>
        }
      },
      {
        title: "退款/变更",
        dataIndex: "salesReturnDetailList",
        key: "salesReturnDetailList",
        render: (text) => {
          let dom = []
          if (text && text.length > 0){
            text.map((item,index)=>{
              // 售后类型：0变更前、1变更后、2退款
              if (["0","1"].includes(item.refundDetailType)){
                if (item.changeStatus){
                  switch (item.changeStatus){
                    case '1':
                      dom.push(<TheButton key={index} onClick={()=>this.onChangeDetailsView(item)}>待处理</TheButton>)
                      break;
                    case '2':
                      dom.push(<TheButton key={index} onClick={()=>this.onChangeDetailsView(item)}>变更成功</TheButton>)
                      break;
                    case '0':
                      dom.push(<TheButton key={index} onClick={()=>this.onChangeDetailsView(item)}>变更关闭</TheButton>)
                      break;
                  }
                }
              }
              else{
                if (item.refundStatus){
                  switch (item.refundStatus){
                    case '1':
                      dom.push(<TheButton key={index} onClick={()=>this.onRefundDetailsView(item)}>待处理</TheButton>)
                      break;
                    case '3':
                      dom.push(<TheButton key={index} onClick={()=>this.onRefundDetailsView(item)}>退款失败</TheButton>)
                      break;
                    case '2':
                      dom.push(<TheButton key={index} onClick={()=>this.onRefundDetailsView(item)}>退款成功</TheButton>)
                      break;
                    case '0':
                      dom.push(<TheButton key={index} onClick={()=>this.onRefundDetailsView(item)}>退款关闭</TheButton>)
                      break;
                  }
                }
              }
            })
          }
          else {
            dom = '-'
          }
          // console.log(dom)
          return dom
        }
      },
      {
        title: "下单时间",
        dataIndex: "orderCreateTime",
        key: "orderCreateTime",
      },
      {
        title: "订单行状态",
        dataIndex: "orderStatus",
        key: "orderStatus",
        render: (text, render) => {
          let label = ''
          switch (text) {
            case 'WAIT_PAY':
              label = "待付款"
              break;
            case 'WAIT_ORDER_TAKING':
              label = "待接单"
              break;
            case 'WAIT_SERVICE':
              label = '待服务'
              break;
            case 'IN_PROCESS':
              label = '服务中'
              break;
            case 'FINISH':
              label = '已完成'
              break;
            case 'CLOSE':
              label = '已关闭'
              break;
            default:
              label = "字段值错误"
          }
          return label
        }
      },
      {
        title: "结算状态",
        dataIndex: "commissionStatus",
        key: "commissionStatus",
        render: (text, render) => {
          let label = ''
          switch (text) {
            case '0':
              label = "未结算"
              break;
            case '1':
              label = "已结算"
              break;
          }
          return label
        }
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (text, render) => {
          return (
              <div>
                <TheButton haspermi={['call:financialReconcile:reconcileOrder:view']} onClick={() => this.onView(render.orderId)}>查看订单</TheButton>
              </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    searchValue: {},
    form_show: true,
    searchOption: [
      { field: 'orderId', label: '订单编号', placeholder: '请输入', required: false, rules: [], type: 'Input',defaultValue: '' },
      { field: 'time', label: '下单时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
      { field: 'serviceType', label: '服务类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ value: '', label: '全部' }, { value: 'FEED', label: '喂养' },{ value: 'CARE', label: '洗护' }], initialValues: '' },
      { field: 'commissionStatus', label: '结算状态', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ value: '', label: '全部' }, { value: '1', label: '已结算' }, { value: '0', label: '未结算' }], initialValues: '' },
      {
        field: 'servicerIdList',
        label: '服务者',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [],
        mode:'multiple',
        otherConfig: {
          filterOption:(input, option) => (option?.children ?? '').includes(input)
        }
      },
    ],
    queryForm: {},
    orderStatus: '',
    tabsItems: [
      {
        key: '',
        label: '全部',
      },
      {
        key: 'WAIT_PAY',
        label: '待付款',
      },
      {
        key: 'WAIT_ORDER_TAKING',
        label: '待分配',
      },
      {
        key: 'WAIT_SERVICE',
        label: '待服务',
      },
      {
        key: 'IN_PROCESS',
        label: '服务中',
      },
      {
        key: 'FINISH',
        label: '已完成',
      },
      {
        key: 'CLOSE',
        label: '已关闭',
      },
    ],
    exportLoading: false, // 导出loading
  };
  componentDidMount() {
    this.getProviderList()
    this.getData()
  }
  getProviderList = () => {
    apiGetProviderList().then(res=>{
      if (res.code === 0){
        const newArr = res.data.map(item=>{
          return {
            label: item.name + '-' +item.providerId,
            value: item.providerId
          }
        })
        let { searchOption } = this.state;
        searchOption[searchOption.length-1].options = newArr;
        this.setState({
          searchOption
        })
      }
    })
  }
  getData = () => {
    let { queryForm, pageData,orderStatus} = this.state
    apiGetMhcOrderBillPage({
      ...pageData,
      ...queryForm,
      orderStatus
    }).then(res=>{
      if (res.code ===0 && res.data){
        this.setState({
          dataSource: res.data,
          pageNo: res.pageNo,
          pageSize: res.pageSize,
          total: res.totalCount
        })
      }
    })
  }
  onView = (id) => {
    this.props.history.push(`/call/financialReconcile/reconcileOrder/detail/${id}`)
  }
  // 服务者详情
  onServeView = (id) => {
    this.props.history.push(`/call/servicer/servicerList/detail/${id}/view`)
  }
  // 变更订单详情
  onChangeDetailsView = (record) => {
    this.props.history.push("/call/order/afterSaleOrder/changeDetails/" + record.salesReturnId)
  }
  // 售后订单详情
  onRefundDetailsView = (record) => {
    this.props.history.push("/call/order/afterSaleOrder/refundDetails/" + record.salesReturnId)
  }
  exportExcel = async () => {
    let { queryForm,orderStatus} = this.state;
    if (_.isEmpty(queryForm) && orderStatus === ''){
      Modal.warning({
        title: '提醒',
        content: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。',
      });
      return
    }
    this.setState({exportLoading: true})
    let params = {
      ...queryForm,
      orderStatus,
    }

    let res = await apiMhcOrderBillExport({...params})
    if (res.code === 0) {
      let th_arr = [
        {
          title: '对账订单',
          prop: '',
          children: [
            {
              title: "订单编号",
              prop: "orderId",
            },
            {
              title: "服务",
              prop: "serviceType",
            },
            {
              title: "服务时间",
              prop: "serviceDate",
            },
            {
              title: "金额(元)",
              prop: "orderAmount",
            },
            {
              title: "实付金额(元)",
              prop: "payAmount",
            },
            {
              title: "退款金额(元)",
              prop: "sumRefundPrice",
            },
            {
              title: "抽佣比例",
              prop: "commissionRatio",
            },
            {
              title: "服务者所得(元)",
              prop: "settlementAmount",
            },
            {
              title: "平台所得(元)",
              prop: "commissionAmount",
            },
            {
              title: "服务者",
              prop: "servicerName",
            },
            {
              title: "退款/变更",
              prop: "salesReturnDetailList",
            },
            {
              title: "下单时间",
              prop: "orderCreateTime",
            },
            {
              title: "订单行状态",
              prop: "orderStatus",
            },
            {
              title: "结算状态",
              prop: "commissionStatus",
            },
          ]
        },
      ]
      let tb_arr = []
      res.data.forEach((item, index) => {
        let serviceType = '';
        let serviceDate = '';
        let commissionStatus = '';
        // 服务
        if (item.serviceType){
          switch (item.serviceType) {
            case 'FEED':
              serviceType = '喂养'
              break;
            case 'CARE':
              serviceType = '洗护'
              break;
          }
          let skuInfo = JSON.parse(item.skuInfo),skuInfoStr = ''
          if (!_.isEmpty(skuInfo)){
            skuInfoStr = skuInfo.specValues.map(item=>{
              return item.specsValue
            }).join('/')
          }
          serviceType = serviceType + "|" + skuInfoStr
        }
        // 服务时间
        if (item.serviceDate){
          serviceDate = `${item.serviceDate} ${item.serviceWeek} ${item.serviceStartTime}~${item.serviceFinishTime}`
          if (item.orderDetailType === 1){
            serviceDate += ' 变更'
          }
        }
        // 退款/变更
        let dom = []
        if (item.salesReturnDetailList && item.salesReturnDetailList.length > 0){
          item.salesReturnDetailList.map((item,index)=>{
            // 售后类型：0变更前、1变更后、2退款
            if (["0","1"].includes(item.refundDetailType)){
              if (item.changeStatus){
                switch (item.changeStatus){
                  case '1':
                    dom.push('待处理')
                    break;
                  case '2':
                    dom.push('变更成功')
                    break;
                  case '0':
                    dom.push('变更关闭')
                    break;
                }
              }
            }
            else{
              if (item.refundStatus){
                switch (item.refundStatus){
                  case '1':
                    dom.push('待处理')
                    break;
                  case '3':
                    dom.push('退款失败')
                    break;
                  case '2':
                    dom.push('退款成功')
                    break;
                  case '0':
                    dom.push('退款关闭')
                    break;
                }
              }
            }
          })
        }
        else {
          dom = '-'
        }

        //结算状态
        switch (item.commissionStatus) {
          case '0':
            commissionStatus = '未结算'
            break
          case '1':
            commissionStatus = '已结算'
        }
        // 订单行状态
        switch (item.orderStatus) {
          case 'WAIT_PAY':
            item.orderStatus = "待付款"
            break;
          case 'WAIT_ORDER_TAKING':
            item.orderStatus = "待接单"
            break;
          case 'WAIT_SERVICE':
            item.orderStatus = '待服务'
            break;
          case 'IN_PROCESS':
            item.orderStatus = '服务中'
            break;
          case 'FINISH':
            item.orderStatus = '已完成'
            break;
          case 'CLOSE':
            item.orderStatus = '已关闭'
            break;
          default:
            item.orderStatus = "-"
        }
        tb_arr.push({
          ...item,
          index: index + 1,
          serviceType,
          serviceDate,
          orderAmount: '￥' + (React.$transNum(item.orderAmount, 2, -2)) || '￥0.00',
          payAmount: '￥' + (React.$transNum(item.payAmount, 2, -2)) || '￥0.00',
          sumRefundPrice: item.sumRefundPrice ? '￥' + (React.$transNum(item.sumRefundPrice, 2, -2)) : '￥0.00',
          commissionRatio: item.commissionRatio ? React.$transNum(item.commissionRatio, 2, -2) + '%' : 0 + '%',
          settlementAmount: item.commissionStatus === '1' ? '￥' + (React.$transNum(item.settlementAmount, 2, -2)) || '￥0.00' : '-',
          commissionAmount: item.commissionStatus === '1' ? '￥' + (React.$transNum(item.commissionAmount, 2, -2)) || '￥0.00' : '-',
          servicerName: item.orderStatus === 'WAIT_ORDER_TAKING' ? '-' : item.servicerName,
          salesReturnDetailList: dom,
          orderStatus: item.orderStatus,
          commissionStatus: commissionStatus
        })
      })
      exportSheetTable({
        fileName: '对账订单',
        tH_data: th_arr,
        tB_data: tb_arr,
        isSheet: true,
        merge: false
      })
    }
    this.setState({exportLoading: false})
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  onFormSearch(values){
    if ('time' in values){
      values.beginOrderCreateTime = moment(values.time[0]).format('yyyy-MM-DD') + ' 00:00:00'
      values.endOrderCreateTime = moment(values.time[1]).format('yyyy-MM-DD') + ' 23:59:59'
      delete values.time
    }
    this.setState({
      pageData:{pageNo:1,pageSize:10},
      queryForm: {...values}
    },()=>{
      this.getData()
    })
  }
  onTabsChange = (key) => {
    this.setState({
      orderStatus: key
    },()=>{
      this.getData()
    })
  }
  render() {
    const {
      loading,
      columns,
      dataSource,
      tabsItems,
      pageData: { pageNo, pageSize },
      total,
      form_show,
      searchOption,
      exportLoading
    } = this.state;
    return (
      <div className="p-layout-box">
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                      onGetValues={(values) => this.onFormSearch(values)}
                      onReset={(values) => this.onReset(values)}
        >
          <TheButton haspermi={['call:financialReconcile:reconcileOrder:export']} loading={exportLoading} type={'default'} size="middle" onClick={this.exportExcel}>导出</TheButton>
        </TheQueryForm>
        <Tabs items={tabsItems} onChange={this.onTabsChange} style={{height: 'auto'}}/>
        <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={dataSource}
            loading={loading}
            // rowKey={(record) => record.orderId}
        />
        <ThePagination
            pageNo={pageNo}
            pageSize={pageSize}
            total={total}
            pageChange={this.pageChange}
        />
      </div>
    )
  }
}
export default ReconcileOrder
